import { PageContainer } from '@ant-design/pro-layout';
import type { FormInstance } from 'antd';
import { message } from 'antd';
import { Button, Divider } from 'antd';
import { useReducer, useRef, useState } from 'react';
import Detail from './mainContent/detail';
import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProFormDateTimePicker, ProFormText } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import styles from './index.less';
import type { RangePickerProps } from 'antd/lib/date-picker';
import { DatePicker } from 'antd';
import moment from 'moment';
import type { orderList } from './types';
import { getOrderTable, overPark } from './service';
import { useModel } from 'umi';
import { ActionType } from '@ant-design/pro-table';

export default () => {
  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    // Can not select days before today and today
    return current && current > moment().endOf('day');
  };
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;
  const formRef = useRef<FormInstance>();
  const [detailId, setDetailId] = useState<string>();
  const [pageName, setPageName] = useState<string>('停车订单');
  const ElementComponent = {
    DetailElement: (
      <Detail
        close={() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          AddClose();
        }}
        id={detailId}
      />
    ),
  };
  const [outVisible, setOutVisible] = useState<boolean>(false);
  const [componentVisibleText, setComponentVisibleText] = useReducer(
    (state: JSX.Element | string, action: string) => {
      switch (action) {
        case 'list':
          setPageName('停车订单');
          return '';
        case 'detail':
          setPageName('订单详情');
          return ElementComponent.DetailElement;
      }
      return state;
    },
    '',
  );

  const AddClose = () => {
    setComponentVisibleText('list');
  };
  const columns: ProColumns<orderList>[] = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '停车场名称',
      dataIndex: 'zoneName',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '车辆属性',
      dataIndex: 'carAttributes',
      hideInSearch: false,
      valueEnum: {
        1: '固定车',
        2: '会员车',
        3: '无牌车',
        4: '临时车',
      },
    },
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      hideInSearch: false,
    },
    {
      title: '车牌颜色',
      dataIndex: 'plateColor',
      hideInSearch: true,
    },
    {
      title: '车辆类型',
      dataIndex: 'carType',
      hideInSearch: false,
      valueEnum: {
        1: '小型车',
        2: '大型车',
        3: '新能源车',
        4: '其他车辆',
      },
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      hideInSearch: false,
      valueEnum: {
        1: { text: '正常', status: 'Success' },
        2: { text: '异常', status: 'Error' },
        3: { text: '欠费', status: 'Warning' },
        4: { text: '未知异常', status: 'None' },
      },
    },
    {
      title: '是否结束',
      dataIndex: 'finishedStatus',
      hideInSearch: false,
      valueEnum: {
        2: { text: '是', status: 'Success' },
        1: { text: '否', status: 'Warning' },
      },
    },
    {
      title: '订单⾦额',
      dataIndex: 'totalAmount',
      hideInSearch: true,
      render: (_, record) => {
        if (record) return <div>{Number(record.totalAmount).toFixed(2)}</div>;
      },
    },
    {
      title: '实收金额',
      dataIndex: 'totalActualAmount',
      hideInSearch: true,
      render: (_, record) => {
        if (record) return <div>{Number(record.totalActualAmount).toFixed(2)}</div>;
      },
    },
    {
      title: '支付状态',
      dataIndex: 'paymentStatus',
      hideInSearch: false,
      valueEnum: {
        0: '未结算',
        1: '未支付',
        2: '已结清',
        5: '已退款',
        6: '部分退款',
        7: '未结清',
        10: '免费',
      },
    },
    {
      title: '入场时间',
      dataIndex: 'beginTime',
      hideInSearch: false,
      renderFormItem: () => {
        return (
          <DatePicker.RangePicker
            showTime
            placeholder={['请选择时间', '请选择时间']}
            disabledDate={disabledDate}
          />
        );
      },
    },
    {
      title: '出场时间',
      dataIndex: 'endTime',
      hideInSearch: false,
      renderFormItem: () => {
        return (
          <DatePicker.RangePicker
            showTime
            placeholder={['请选择时间', '请选择时间']}
            disabledDate={disabledDate}
          />
        );
      },
    },
    {
      title: '支付方式',
      dataIndex: 'paymentType',
      hideInSearch: false,
      valueEnum: {
        1: '微信H5',
        2: '支付宝H5',
        3: '微信支付',
        4: '支付宝支付',
        20: '现金支付',
      },
    },
    {
      fixed: 'right',
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                setDetailId(record.id);
                setComponentVisibleText('detail');
              }}
            >
              详情
            </a>
            <Divider type="vertical" />
            {record.stoppable && (
              <a
                onClick={() => {
                  setOutVisible(true);
                  setDetailId(record.id);
                }}
              >
                强制驶出
              </a>
            )}
          </>
        );
      },
    },
  ];
  return (
    <PageContainer
      title={
        <div>
          {componentVisibleText && (
            <Button
              // disabled={returnPlay}
              type="link"
              onClick={() => {
                setComponentVisibleText('list');
              }}
            >
              <img
                className={styles.toolBarImg}
                src={'/icons/arrow-return-left.svg'}
                alt="Picture of the author"
                width="21"
                height="21"
              />
            </Button>
          )}
          {pageName}
        </div>
      }
    >
      {!componentVisibleText && (
        <ProTable<any>
          actionRef={actionRef}
          rowKey="parkingOrderId"
          columns={columns}
          scroll={{ x: true }}
          style={{ whiteSpace: 'nowrap' }}
          columnEmptyText="-"
          headerTitle="订单列表"
          pagination={{
            size: 'default',
            showQuickJumper: true,
            showSizeChanger: true,
            defaultPageSize: 10,
          }}
          request={async (param) => {
            const res: any = await getOrderTable(param);
            return { ...res, data: res.data.list, success: true, total: res.data.total };
          }}
        />
      )}
      {componentVisibleText}
      <ModalForm
        layout="horizontal"
        width={550}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        onFinish={async (values) => {
          const res = await overPark(detailId!, values?.dateTime);
          if (res && res.code == 0) {
            setOutVisible(false);
            message.success('车辆驶出成功');
            actionRef.current?.reload();
            return true;
          } else {
            message.error('车辆驶出失败' + res?.message);
            return false;
          }
        }}
        open={outVisible}
        title="驶出订单"
        formRef={formRef}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setOutVisible(false);
          },
          centered: true,
          footer: null,
        }}
      >
        <ProFormText
          width={'sm'}
          label="订单编号"
          name="id"
          disabled
          required={true}
          initialValue={detailId}
        />
        <ProFormDateTimePicker
          width={'sm'}
          name="dateTime"
          label="驶出时间"
          tooltip={'未输⼊驶出时间，默认为此刻 '}
          fieldProps={{
            format: (value) => value.format('YYYY-MM-DD HH:mm:ss'),
          }}
        />
      </ModalForm>
    </PageContainer>
  );
};
